//
//  ZQSeeBigPictureViewController.m
//  BuDeJie
//
//  Created by 仲琦 on 16/4/16.
//  Copyright © 2016年 仲琦. All rights reserved.
//

#import "ZQSeeBigPictureViewController.h"
#import "UIImageView+Download.h"
#import "ZQTopic.h"
#import <SVProgressHUD.h>
#import <Photos/Photos.h>

@interface ZQSeeBigPictureViewController ()

@property (weak, nonatomic) IBOutlet UIButton *saveBtn;

/** imageView */
@property (nonatomic, strong)UIImageView *imageView;

// 在interface中写方法的声明，是为了点语法有智能提示
- (PHFetchResult<PHAsset *> *)createdAssets;
- (PHAssetCollection *)createdCollection;

@end
@implementation ZQSeeBigPictureViewController


-(void)viewDidLoad
{
    
    [super viewDidLoad];
    
    //创建scrollView作为底层滚动view
    UIScrollView *scrollview = [[UIScrollView alloc]init];
    scrollview.frame = [UIScreen mainScreen].bounds;
    //将scrollView添加到第0个子控件
    [self.view insertSubview:scrollview atIndex:0];
    
    //创建视图view
    UIImageView *imageV = [[UIImageView alloc]init];
    //下载文件
    [imageV sd_setImageWithURL:[NSURL URLWithString:self.topic.image1] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image == nil) return ;
        self.saveBtn.enabled = YES;
    }];
    //固定宽度与x值
    imageV.zq_width = scrollview.zq_width;
    imageV.zq_x = 0;
    [scrollview addSubview:imageV];
    self.imageView =imageV;
    //计算图片的高度
    imageV.zq_height = imageV.zq_width * self.topic.height / self.topic.width;
    
    if (imageV.zq_height >= ZQScreenH) {
        imageV.zq_y = 0;
        scrollview.contentSize = CGSizeMake(0, imageV.zq_height);
        
    }else{
        imageV.zq_centerY = scrollview.zq_height * 0.5;
    }
}

/**
 *  返回按钮
 */
- (IBAction)goBackBtnClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  从写属性的getter方法
 *  保存图片到相册
 */
- (PHFetchResult<PHAsset *> *)createdAssets
{
    __block NSString *creatdAssetId = nil;
    
    //保存图片到<相机胶卷>
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        creatdAssetId = [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
    } error:nil];
    
    //判断是否创建完成
    if (creatdAssetId == nil) return nil;
    
    //保存完毕后取出图片
    return [PHAsset fetchAssetsWithLocalIdentifiers:@[creatdAssetId] options:nil];
    
}

/**
 *  从写属性的getter方法
 *  创建一个软件名称的相册
 */
- (PHAssetCollection *)createdCollection
{
    
    //获取软件的名字作为相册的标题
    NSString *title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
    
    //获得所有的自定义相册
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    //判断系统中是否有该软件名的相册
    for (PHAssetCollection *collection in collections) {
        if ([collection.localIdentifier isEqualToString:title]) {
            return collection;
        }
    }
    
    //代码执行到这里说明还没有创建相册
     __block NSString *createdCollectionId = nil;
   
    //创建一个新的相册 名字为软件名
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
    } error:nil];
    
    //判断是否创建成功,
    if (createdCollectionId == nil) return nil;
    
    //创建完毕取出相册
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionId] options:nil].firstObject;
}


/**
 *  保存图片至自定义相册
 */
- (void)saveImageIntoAlbum
{
    // 获得相片
    PHFetchResult<PHAsset *> *createdAssets = self.createdAssets;
    
    // 获得相册
    PHAssetCollection *createdCollection = self.createdCollection;
    
    if (createdAssets == nil || createdCollection == nil) {
        [SVProgressHUD showErrorWithStatus:@"保存失败！"];
        return;
    }
    
    //将刚才添加到<相机胶卷>的图片,引用(添加)到<自定义相册>
    
    NSError *error = nil ;
    
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdCollection];
        //将图片保存至相册的第0 个位置
        [request insertAssets:createdAssets atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    
    //判断保存是否成功
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败"];
    }else
    {
        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
    }


}

/**
 *  点击按钮保存图片
 */
- (IBAction)saveImageBtnClick {
    
    //获取用户配置信息
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    
    //取出用户配置,在主线程判断用户配置
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (status) {
                case PHAuthorizationStatusAuthorized: {//点击过允许按钮
                    //  保存图片到相册
                    [self saveImageIntoAlbum];
                    break;
                }
                    
                case PHAuthorizationStatusDenied: {//点击过拒绝按钮
                    //仅二次提醒,
                    if (oldStatus == PHAuthorizationStatusNotDetermined) return;
                    
                    ZQLog(@"提醒用户打开相册的访问开关");
                    break;
                }
                    
                case PHAuthorizationStatusRestricted: {//系统原因无法访问
                    [SVProgressHUD showErrorWithStatus:@"因系统原因，无法访问相册！"];
                    break;
                }
                    
                default:
                    break;
            }

        });
    }];

}


@end
